using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Timers;
using SpoonCore2.Client;
using SpoonCore2.Message;

namespace SpoonCore2.Service.Monitor
{
	public class MonitorService : AbstractService
	{
		private readonly SpoonIdentifier _id = SpoonIdentifier.Parse("DC98FAC6965FA0319BEAA31BFA6BF9F8");
		private readonly SortedList<string, List<MonitorItem>> _data = new SortedList<string, List<MonitorItem>>();

		public override SpoonIdentifier Id { get { return _id; } }

		public override void Dispose()
		{

		}

		public override void Init()
		{
			Handler.Register(new MessageHandler.ReceiveMessageHandler<MonitorMessage>(MessageReceive));
		}

		private void MessageReceive(ClientInfo sender, MonitorMessage message)
		{
			if(message.Type == MonitorMessage.MessageType.Request)
			{
				Lookup(message);

				message.Type = MonitorMessage.MessageType.Response;
				sender.Send(message);
			}
			else if(message.Type == MonitorMessage.MessageType.Response)
			{
				//TODO
			}
		}

		private void Lookup(MonitorMessage message)
		{
			foreach (MonitorMessage.RequestItem item in message.Request)
			{
				if(_data.ContainsKey(item.Key))
				{
					if(!message.Data.ContainsKey(item.Key)) message.Data.Add(item.Key, new List<MonitorItem>());
					foreach (MonitorItem monitorItem in _data[item.Key])
					{
						if(monitorItem.Timestamp >= item.Start && monitorItem.Timestamp <= item.Stop)
						{
							message.Data[item.Key].Add(monitorItem);
						}
					}
				}
			}
		}

		public void Add(string key, string value)
		{
			if(_data.ContainsKey(key))
			{
				_data[key].Add(new MonitorItem(value));
			}
		}

		public class MonitorItem
		{
			private readonly DateTime _timestamp = DateTime.Now;
			private readonly string _value;

			public MonitorItem(BinaryReader br)
			{
				_timestamp = new DateTime(br.ReadInt64());
				_value = br.ReadString();
			}

			public MonitorItem(string value)
			{
				_value = value;
			}

			public DateTime Timestamp
			{
				get { return _timestamp; }
			}

			public string Value
			{
				get { return _value; }
			}

			public void GetBytes(BinaryWriter bw)
			{
				bw.Write(_timestamp.Ticks);
				bw.Write(_value);
			}
		}

		public override void Start()
		{
			
		}

		public override void Stop()
		{
			
		}
	}
}
